package com.pxdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 添加缓存
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value, Long time, TimeUnit unit){
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    /**
     * 添加缓存并设置逻辑过期时间
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setLogical(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 封装缓存穿透的解决方法
     *
     * @return
     */
    public <R,ID> R queryWithPassThrough(String key, ID id, Class<R> type, Function<ID,R> dbFallback,Long time, TimeUnit unit) {
        //判断redis中是否有数据
        String jsonShop = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //如果存在直接返回数据
        if (!StrUtil.isBlank(jsonShop)) {
            R sp = JSONUtil.toBean(jsonShop, type);
            //log.info("查询到redis数据返回");
            return sp;
        }
        //如果查询到空值直接返回错误信息
        if (jsonShop != null) {
            //log.info("查询到不存在的店铺 返回空值");
            return null;
        }
        //如果不存在
        //查询数据库是否有数据
        R shop = dbFallback.apply(id);
        //判断查询到是否有数据
        if (BeanUtil.isEmpty(shop)) {
            //将空的值写入redis
            redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
       this.set(key,shop,time,unit);
        return shop;
    }
}
